/*
 * @Descripttion: 
 * @Author: zhanyi
 * @Date: 2021-10-20 14:10:56
 * @FilePath: \wczd-mobile\src\utils\request.js
 */
import { getToken } from '@/utils/auth'//获取token
import changeData from '@/utils/changeData'// 解决params传值

function request (obj) {
  return new Promise((resolve, reject) => {
    const baseUrl = process.uniEnv.baseUrl
    var method = obj.method || "GET";
    var url = baseUrl + obj.url || "";
    var data = obj.data || {};
    let token = getToken();
    var header = obj.header || {
      "Content-Type": obj.contentType || "application/json",
      'Authorization': token ? 'Bearer ' + token : ''
    }
    var params = obj.params || {}
    if (obj.data && obj.data.pageNum) {
      params.pageNum = obj.data.pageNum
    }
    if (obj.data && obj.data.pageSize) {
      params.pageSize = obj.data.pageSize
    }
    if (params&&params!={}) {
      url = changeData.dataToParams(url, params)
    }
    uni.request({
      url: url,
      data: data,
      method: method,
      timeout: 10000,
      header: header,
      dataType: 'json',
      success: ((res) => {
        if (res.statusCode === 403 || res.statusCode === 401) {
          uni.reLaunch({// 错误处理，返回登录页
            url: '/pages/login/login'
          })
        } else if (res.statusCode === 200) {
					const code = res.data.code || 200
					if (code === 401) {
						resolve(res.data)
						uni.showToast({
							title: '登录过期',
							icon: "none",
							duration: 2000
						});
						uni.reLaunch({// 错误处理，返回登录页
							url: '/pages/login/login'
						})
					} else if (code === 500) {
					  uni.showModal({
					      title: '提示',
					      content: res.data.msg||"操作失败",
								showCancel: false,
					      success: function (res) {}
					  });
					  resolve(res.data)
					} else if (code !== 200) {
					  uni.showModal({
					      title: '提示',
					      content: res.data.msg||"操作失败",
								showCancel: false,
					      success: function (res) {}
					  });
					  reject(err)
					} else {
						resolve(res.data)
					}
        }
      }),
      fail: ((err) => {
        uni.showToast({
          title: '请求接口失败',
					icon: 'none',
          duration: 2000
        })
        reject(err)
      })
    })
  })
}
export default request
